package com.gin.danbooru.main

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.gin.danbooru.api.PostsApi
import com.gin.danbooru.factory.JsoupConverterFactory
import com.gin.danbooru.interceptor.LogInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 主类
 * @author BX-Gin
 * @from 2024/2/27 10:06
 */
class Danbooru(private val retrofit: Retrofit) {

    companion object {
        const val DEFAULT_HOST = "https://danbooru.donmai.us/"

        @JvmStatic
        val MAPPER: ObjectMapper = ObjectMapper()
            //美化输出
            .enable(SerializationFeature.INDENT_OUTPUT)
            .enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT)
            .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            //true - 遇到没有的属性就报错 false - 没有的属性不会管，不会报错
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            // 支持 ZonedDateTime
            .registerModule(JavaTimeModule())


        /**
         * 创建OkHttpClient实例
         */
        @JvmStatic
        fun obtainOkHttpClient(): OkHttpClient {
            return OkHttpClient.Builder()
                .addInterceptor(LogInterceptor())
                .callTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build()
        }

        /**
         * 创建Retrofit实例
         */
        @JvmStatic
        fun obtainRetrofit(client: OkHttpClient, baseUrl: String = DEFAULT_HOST): Retrofit {
            return Retrofit.Builder()
                .client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(JsoupConverterFactory())
                .addConverterFactory(JacksonConverterFactory.create(MAPPER))
                .build()
        }
    }

    fun postsApi(): PostsApi = retrofit.create(PostsApi::class.java)

}